#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->port->setText("8899");

    setWindowTitle("河师大软件学院附属医院挂号处");
    m_s=new QTcpServer(this);

    db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName(DATABASE_FILE_PATH); // 替换为实际的数据库文件名
        if (!db.open()) {
            QMessageBox::warning(this, "数据库错误", "无法打开数据库");
        }


    connect(m_s, &QTcpServer::newConnection,this,[=](){
         m_tcp =m_s->nextPendingConnection();
        m_status->setPixmap(QPixmap(":/OIP-C.jpg").scaled(20,20));

        connect(m_tcp,&QTcpSocket::readyRead,this,[=](){
            QByteArray data =m_tcp->readAll();
            ui->record ->append("患者预约信息:"+data);      //可将此预约信息data存往数据库

            storeDataInDatabase(data);
        });

        connect(m_tcp,&QTcpSocket::disconnected,this,[=]()
        {m_tcp->close();
         m_tcp->deleteLater();
         m_status->setPixmap(QPixmap(":/OIP-C (1).jpg").scaled(20,20));
        });

    });

m_status=new QLabel;
m_status->setPixmap(QPixmap(":/OIP-C (1).jpg").scaled(20,20));
ui->statusbar->addWidget(new QLabel("连接状态:"));
ui ->statusbar->addWidget(m_status);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_setlisten_clicked()
{
      unsigned short port =ui->port->text().toUShort();
      m_s->listen(QHostAddress::Any,port);
      ui->setlisten->setDisabled(true);
}


void MainWindow::on_sendMsg_clicked()
{
    QString msg=ui->msg ->toPlainText();
    m_tcp->write(msg.toUtf8());
    ui->record->append("挂号处say:"+msg);
}
void MainWindow::storeDataInDatabase(const QByteArray &data)
{
    QSqlQuery query;
    query.prepare("INSERT INTO appointments (appointment_info) VALUES (:info)");
    query.bindValue(":info", data);

    if (query.exec()) {
        qDebug() << "患者预约信息已成功存储到数据库";
    } else {
        qDebug() << "存储患者预约信息到数据库时出错: " << query.lastError();
    }
}

void MainWindow::displayDatabaseContents()
{
    QSqlQuery query;
    if (query.exec("SELECT * FROM appointments"))
    {
        QString allAppointments;
        while (query.next())
        {
            QByteArray appointmentInfo = query.value("appointment_info").toByteArray();
            allAppointments += "预约信息: " + QString(appointmentInfo) + "\n";
        }

        if (!db.isOpen())
        {
            qDebug() << "数据库未打开，无法查询内容";
            return;
        }

        ui->textEdit->setText(allAppointments);
    }
    else
    {
        qDebug() << "查询数据库内容出错: " << query.lastError();
    }
}

void MainWindow::on_pushButton_clicked()
{
 displayDatabaseContents();
}
